package com.donn.securitycontrolplatform.expection;


import com.donn.securitycontrolplatform.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName GlobalExceptionHandler
 * @Author Glenn
 * @Date 2021/8/17 10:12
 * @Description GlobalExceptionHandler
 * @Version 2.1
 */
@ControllerAdvice
@Slf4j
@ResponseBody  //表示返回的对象，Spring会自动把该对象进行json转化，最后写入到Response中。
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class) //表示让Spring捕获到所有抛出的BusinessException异常，并交由这个被注解的方法处理。
    @ResponseStatus(HttpStatus.OK)
        //表示设置状态码。
    Result handleException(BusinessException e) {
        log.info("捕獲到自定义异常，异常是=" + e.getResultCode());

        return Result.init(e.getResultCode());
    }


    //添加全局参数异常处理流程，根据需要设置需要处理的异常   数据绑定异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result MethodArgumentNotValidHandler(HttpServletRequest request,
                                                MethodArgumentNotValidException exception) {
        log.info("捕獲到参数异常，异常是=" + exception.getMessage());
        List<ObjectError> errors = exception.getBindingResult().getAllErrors();
        StringBuffer errorMsg = new StringBuffer();
        errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
        return Result.init(10000, errorMsg.toString(),"");
    }

    @ExceptionHandler(Exception.class)
    public Result ExceptionHandler(HttpServletRequest request,
                                   Exception exception) {
        exception.printStackTrace();
        return Result.init(10000, exception.toString(),"");
    }


    @ExceptionHandler(IOException.class)
    public Result IOExceptionHandler(HttpServletRequest request,
                                   Exception exception) {
        exception.printStackTrace();
        return Result.init(10000, exception.toString(),"");
    }



}
